package com.example.myapplication.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.example.myapplication.Fruit;
import com.example.myapplication.R;

import java.util.List;

public class FruitAdapter  extends ArrayAdapter<Fruit> {
    private int resourceId;
    //自定义一个构造器 主要用来初始化对象  列表作为数据载体 ---》水果作为实体
    public FruitAdapter(@NonNull Context context, int resourceId, List<Fruit> fruitList) {
        super(context, resourceId, fruitList);
        this.resourceId = resourceId;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        Fruit fruit = getItem(position);
        View view;
        ViewHolder viewHolder;

        //Log.d("FruitAdapter","position:"+position+"convertView:"+convertView);
//        convertView是否为空
//        优化的第一步
        if(convertView == null){
            //创建视图 将视图对应的视图提取出来
            view = LayoutInflater.from(getContext()).inflate(resourceId,parent,false);

            viewHolder = new ViewHolder();
            viewHolder.ivFruit = view.findViewById(R.id.fruit_image);
            viewHolder.tvFruit = view.findViewById(R.id.fruit_name);
            //保存viewHolder对象
            view.setTag(viewHolder);

        }
        else
        {
           view = convertView;
           viewHolder =(ViewHolder) view.getTag();
        }

        viewHolder.tvFruit.setText(fruit.getName());
        viewHolder.ivFruit.setImageResource(fruit.getImageId());
        return view;

    }

    class ViewHolder{
        ImageView ivFruit;
        TextView tvFruit;
    }



}

